<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\ChatLog;
use app\common\model\Note;
use RongCloud\RongCloud;
use think\Db;

class Chat  extends Api
{
  protected $noNeedLogin = [''];
  protected $noNeedRight = ['*'];
  protected $rongyun;

  /**
   * 发送消息
   *
   * @param mixed type     消息类型 1=文字 2=图片 3=语音
   * @param mixed content  消息内容
   * @param mixed touid    接收方uid
   * @return void
   */
  public function send()
  {
    $uid = $this->auth->id;
    $touid = $this->request->request('touid');
    $type = $this->request->request('type');
    $content = $this->request->request('content');
    $postion=$this->auth->postion;

    if ($uid == $touid) {
      $this->error("不能给自己发消息");
    }
    if($touid){
        $touser=\app\admin\model\User::where(['id'=>$touid,'del_flag'=>0])->find();
        if(!$touser){
            $this->error('对方不存在');
        }

    }
    //分组
    $item = [$uid, $touid];
    sort($item);
    $data = [
      'type'    => $type,
      'content' => $content,
      'uid'     => $uid,
      'touid'   => $touid,
      'is_read' => 0,
      'lab'   => $item[0] . '-' . $item[1],
      'postion'=>$postion
    ];

    //调用融云发送消息

    $this->sendMsg($uid, $touid, $data);

    //插入数据库
    $result = ChatLog::create($data);
    if (!$result) {
      $this->error('发送失败');
    }
    $this->success('发送成功');
  }

  /**
   * @param $uid
   * @param $touid
   * @param $data
   * @return //聊天记录
   */

  public function record(){
    $user = $this->auth->getUser();
    $uid  = $user->id;
    $avatar   = $user->avatar;
    $nickname = $user->nickname;
    $touid = $this->request->request('touid');
    $page  = $this->request->request('page', 1);
    $postion=\app\admin\model\User::where(['id'=>$touid])->value('postion');
    if($postion==1){
      $to_user = \app\admin\model\User::get(['id'=>$touid]);
      $to_user_nickname = $to_user['nickname'];
      $to_user_avatar   = $to_user['avatar'];
    }else if($postion==2){
        $to_user=\app\common\model\Technician::get(['uid'=>$touid]);
        $to_user_nickname = $to_user['technician_name'];
        $to_user_avatar   = $to_user['technician_avatar'];
    }else if($postion==3){
        $to_user=\app\common\model\Store::get(['uid'=>$touid]);
        $to_user_nickname = $to_user['name'];
        $to_user_avatar   = $to_user['serve_image']?:config('site.record_avatar');
    }else if($postion==4){
        $to_user = \app\admin\model\User::get(['id'=>$touid]);
        $to_user_nickname = $to_user['nickname'];
        $to_user_avatar   = $to_user['avatar'];
    }

    //聊天记录
    $list=ChatLog::where(['uid'=>$uid,'touid'=>$touid])->whereOr(function ($query) use ($touid, $uid) {
      $query->where(['uid' => $touid, 'touid' => $uid]);
    })->order('id','desc')->page($page, 20)->select();
    if ($list) {
      foreach ($list as $v) {
        $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
        $v['sender'] = $uid == $v['uid'] ? 1 : 0;//发送人
        if ($v['uid'] == $uid) {
          $v['avatar'] = $avatar;
          $v['nickname'] = $nickname;
        }else{
          $v['avatar'] =$to_user_avatar;
          $v['nickname'] =$to_user_nickname;
        }
        //消息类型处理
//        if ($v['type'] == 2) {
//          $v['content'] = $v['content'];
//        }
        if ($v['type'] == 3) {
          $v['content'] = json_decode(html_entity_decode($v['content']));
        }
      }
      //改为已读
      ChatLog::where(['uid' => $uid, 'touid' => $touid, 'is_read' => 0])->update(['is_read' => 1]);
    }
    $list = array_reverse($list); //数组翻转
    $this->success("请求成功", $list);
  }


  /**
   * @param $uid
   * @param $touid
   * @param $data
   * @return array  用户聊天列表
   */
  public function userlist(){
    $uid = $this->auth->id;
    $sql = "SELECT * FROM ( 
                    SELECT * FROM `xin_chat_log` where touid=$uid or uid = $uid  having 1 ORDER BY createtime desc
                ) `tmp` GROUP BY tmp.lab";
    $list = Db::query($sql);
    foreach ($list as &$v) {

      switch ($v['type']) {
        case '2':
          $v['content'] = "[图片]";
          break;
        case '3':
          $v['content'] = "[音频]";
          break;
        default:
          # code...
          break;
      }
//        $user = \app\admin\model\User::get($v['uid']);
//        $nickname = $user['nickname'];
//        $avatar   = $user['avatar'];
//      $v['nickname']   = $nickname;
//      $v['avatar']     = $avatar;
      $store=\app\common\model\Store::where(['uid'=>$v['touid']])->find();
      if($store){
        $v['store_nickname']=$store->name;
        $v['store_avater']=$store->serve_image?:config('site.record_avatar');
      }
      $v['createtime'] = date("Y-m-d H:i:s", $v['createtime']);
            $serve_logo = config('site.logo');
            $serve_name = config('site.serve_name');
            $user = \app\admin\model\User::where(['id' => 1])->find();
            if ($v['touid'] == 1) {
                $v['serve_content'] = $v['content'];
                $v['serve_logo'] = $serve_logo;
                $v['serve_name'] = $serve_name;
                $v['uid'] = $user->id;
                $v['serve_time'] = date("Y-m-d H:i:s", $this->auth->logintime);
            }
        $serve_logo = config('site.logo');
        $serve_name = config('site.serve_name');
        $serve['serve_logo'] = $serve_logo;
        $serve['serve_name'] = $serve_name;
        $serve['serve_content'] = '您好,您想咨询什么呢';
        $user = \app\admin\model\User::where(['id' => 1])->find();
        $serve['uid'] = $user->id;
        $serve['serve_time'] = date("Y-m-d H:i:s", $this->auth->logintime);
            unset($v);
        }
    $serve=[];
    if(!$list){
        $serve_logo = config('site.logo');
        $serve_name = config('site.serve_name');
        $serve['serve_logo'] = $serve_logo;
        $serve['serve_name'] = $serve_name;
        $serve['serve_content'] = '您好,您想咨询什么呢';
        $user = \app\admin\model\User::where(['id' => 1])->find();
        $serve['uid'] = $user->id;
        $serve['serve_time'] = date("Y-m-d H:i:s", $this->auth->logintime);
    }
    $this->success("请求成功", ['list'=>$list,'serve'=>$serve??[]]);
  }


  /**
   * @param $uid
   * @param $touid
   * @param $data
   * @return array  店铺聊天列表
   */
  public function storemessage(){
    $uid = $this->auth->id;
    $sql = "SELECT * FROM ( 
                    SELECT * FROM `xin_chat_log` WHERE touid=$uid or uid = $uid   having 1 ORDER BY createtime desc
                ) `tmp` GROUP BY tmp.lab";
    $list = Db::query($sql);
    foreach ($list as &$v) {

      switch ($v['type']) {
        case '2':
          $v['content'] = "[图片]";
          break;
        case '3':
          $v['content'] = "[音频]";
          break;
        default:
          # code...
          break;
      }
//        $user = \app\admin\model\User::get($v['uid']);
//        $nickname = $user['nickname'];
//        $avatar   = $user['avatar'];
//      $v['nickname']   = $nickname;
//      $v['avatar']     = $avatar;

      $technician=\app\common\model\Technician::where(['uid'=>$v['touid']])->find();
      if($technician){
        $v['technician_nickname']=$technician->technician_name;
        $v['technician_avatar']=$technician->technician_avatar;
      }else{
          $user=\app\common\model\User::where(['id'=>$v['uid']])->find();
      if($user){
        $v['nickname']=$user->nickname;
        $v['avater']=$user->avatar;
      }
      }
      $v['createtime'] = date("Y-m-d H:i:s", $v['createtime']);
        $serve=[];
            $serve_logo=config('site.logo');
            $serve_name=config('site.serve_name');
            $user=\app\admin\model\User::where(['id'=>1])->find();
            if($v['touid']==1){
                $v['serve_content']=$v['content'];
                $v['serve_logo']=$serve_logo;
                $v['serve_name']=$serve_name;
                $v['uid']=$user->id;
                $v['serve_time']= date("Y-m-d H:i:s", $this->auth->logintime);
            }
            $serve['serve_logo']=$serve_logo;
            $serve['serve_name']=$serve_name;
            $serve['serve_content']='您好,您想咨询什么呢';
            $serve['uid']=$user->id;
            $serve['serve_time']= date("Y-m-d H:i:s", $this->auth->logintime);
            $note=Note::where(['uid'=>$uid])->field('createtime,content')->find();
            if($note){
                $note['content']=$note->content;
                $note['createtime']=date('Y-m-d H:i:s',$note->createtime);
            }
      unset($v);
    }
      if(!$list){
          $serve_logo = config('site.logo');
          $serve_name = config('site.serve_name');
          $serve['serve_logo'] = $serve_logo;
          $serve['serve_name'] = $serve_name;
          $serve['serve_content'] = '您好,您想咨询什么呢';
          $user = \app\admin\model\User::where(['id' => 1])->find();
          $serve['uid'] = $user->id;
          $serve['serve_time'] = date("Y-m-d H:i:s", $this->auth->logintime);
          $note=Note::where(['uid'=>$uid])->field('createtime,content')->find();
          if($note){
              $note['content']=$note->content;
              $note['createtime']=date('Y-m-d H:i:s',$note->createtime);
          }
      }
      $this->success("请求成功",['list'=>$list,'serve'=>$serve??[],'note'=>$note??[]]);
  }


  /**
   * @param $uid
   * @param $touid
   * @param $data
   * @return array  技师聊天列表
   */
  public function technicianmessage(){

    $uid = $this->auth->id;
    $sql = "SELECT * FROM ( 
                    SELECT * FROM `xin_chat_log` WHERE touid = $uid or uid = $uid having 1 ORDER BY createtime desc
                ) `tmp` GROUP BY tmp.lab";
    $list = Db::query($sql);
    foreach ($list as &$v) {

      switch ($v['type']) {
        case '2':
          $v['content'] = "[图片]";
          break;
        case '3':
          $v['content'] = "[音频]";
          break;
        default:
          # code...
          break;
      }
      $store=\app\common\model\Store::where(['uid'=>$v['touid']])->find();
      $user=\app\admin\model\User::where(['id'=>$store['uid']])->find();
      if($store){
        $v['store_nickname']=$store->name??$user->nickname;
        $v['store_avater']=$store->serve_image??$user->avatar;
      }else{
          $user=\app\admin\model\User::where(['id'=>$v['touid']])->find();
          $v['store_nickname']=$user['nickname'];
          $v['store_avater']=$user['avatar'];
      }
      $v['createtime'] = date("Y-m-d H:i:s", $v['createtime']);
        $serve=[];
            $serve_logo=config('site.logo');
            $serve_name=config('site.serve_name');
            $user=\app\admin\model\User::where(['id'=>1])->find();
            if($v['touid']==1){
                $v['serve_content']=$v['content'];
                $v['serve_logo']=$serve_logo;
                $v['serve_name']=$serve_name;
                $v['uid']=$user->id;
                $v['serve_time']= date("Y-m-d H:i:s",$user->logintime);
            }else{
                $serve['serve_logo']=$serve_logo;
                $serve['serve_name']=$serve_name;
                $serve['serve_content']='您好,您想咨询什么呢';
                $serve['uid']=$user->id;
                $serve['serve_time']= date("Y-m-d H:i:s", $user->logintime);
            }

        unset($v);
    }
    if(!$list){
        $serve_logo=config('site.logo');
        $serve_name=config('site.serve_name');
        $user=\app\admin\model\User::where(['id'=>1])->find();
        $serve['serve_logo']=$serve_logo;
        $serve['serve_name']=$serve_name;
        $serve['serve_content']='您好,您想咨询什么呢';
        $serve['uid']=$user->id;
        $serve['serve_time']= date("Y-m-d H:i:s", $user->logintime);
    }
      $this->success("请求成功", ['list'=>$list,'serve'=>$serve??[]]);
  }


    /**
     * @param $uid
     * @param $touid
     * @param $data
     * @return array  客服聊天列表
     */

    public function servemessage(){
        $uid = $this->auth->id;
        $sql = "SELECT * FROM ( 
                    SELECT * FROM `xin_chat_log` WHERE touid = $uid or uid = $uid having 1 ORDER BY createtime desc
                ) `tmp` GROUP BY tmp.lab";
        $list = Db::query($sql);
        foreach ($list as &$v) {

            switch ($v['type']) {
                case '2':
                    $v['content'] = "[图片]";
                    break;
                case '3':
                    $v['content'] = "[音频]";
                    break;
                default:
                    # code...
                    break;
            }
//        $user = \app\admin\model\User::get($v['uid']);
//        $nickname = $user['nickname'];
//        $avatar   = $user['avatar'];
//      $v['nickname']   = $nickname;
//      $v['avatar']     = $avatar;
            $store=\app\common\model\Store::where(['uid'=>$v['touid']])->find();
            $user=\app\admin\model\User::where(['id'=>$store['uid']])->find();
            if($store){
                $v['store_nickname']=$store->name;
                $v['store_avater']=$store->serve_image??$user->avatar;
            }
            $technician=\app\common\model\Technician::where(['uid'=>$v['touid']])->find();
            if($technician){
                $v['technician_nickname']=$technician->technician_name;
                $v['technician_avatar']=$technician->technician_avatar;
            }
            $user=\app\admin\model\User::where(['id'=>$v['touid']])->find();
            if($user){
                $v['nickname']=$user->nickname;
                $v['avatar']=$user->avatar;
            }
            $serve_logo=config('site.logo');
            $serve_name=config('site.serve_name');
            $v['serve_logo']=$serve_logo;
            $v['serve_name']=$serve_name;
            $v['serve_contnet']='您好,您想咨询什么呢';
            $v['createtime'] = date("Y-m-d H:i:s", $v['createtime']);
            unset($v);
        }
        $this->success("请求成功", $list);
    }



  //融云发送消息
  function sendMsg($uid, $touid, $data)
  {
    $APPKEY =  'bmdehs6pb8c4s';
    $APPSECRET = 'qSdPibEmOX';
    $rongyun = new RongCloud($APPKEY, $APPSECRET);
    $message = [
      'senderId' => $uid, //发送人 id
      'targetId' => $touid, //['uPj70HUrRSUk-ixtt7iIGc'],//接收人 id
      "objectName" => 'RC:TxtMsg', //'WS:chat_json',//'RC:TxtMsg',//消息类型 文本
      'content' => json_encode(['content' => $data], JSON_UNESCAPED_UNICODE) //消息内容
    ];
    $qwe = $rongyun->getMessage()->Person()->send($message);
    return $qwe;
  }
}